package com.example.smartcity_poverty.ui.AllService.GovernmentHotLine.Activity

import android.app.Activity
import android.content.Intent
import android.database.Cursor
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.util.Log
import android.view.MenuItem
import android.view.View
import android.widget.RadioButton
import android.widget.RadioGroup
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import com.example.smartcity_poverty.App.Companion.getToken
import com.example.smartcity_poverty.App.Companion.url
import com.example.smartcity_poverty.R
import com.example.smartcity_poverty.logic.Repository.api
import com.example.smartcity_poverty.logic.util.Util.show
import kotlinx.android.synthetic.main.activity_add_gm_hot_line.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONObject


/**
 * 新建诉求页
 */
class AddGmHotLineActivity : AppCompatActivity() {

    private val imageCode = 2

    // 选择的照片Uri
    private lateinit var imagePath: String

    private val list = listOf<String>(
        "积分落户","市政维修","道路设施","便民设施",
        "物价问题","教育相关","疫情问题","公共交通问题",
        "人才招聘问题","生育政策","企业政策咨询","购房政策咨询",
        "市政规划咨询","黑恶势力举报","传销诈骗举报")

    private val listNumber = listOf<Int>(
        8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23
    )

    private var tvName: String? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        setContentView(R.layout.activity_add_gm_hot_line)
        title = "新建诉求"

        val id = intent.getStringExtra("id")

        if (id != null){
            addPostOk.setOnClickListener {
                if (addTitle.text.toString().isNotEmpty() &&
                    addUserThis.text.toString().isNotEmpty() &&
                    addContent.text.toString().isNotEmpty() &&
                    addPhone.text.toString().isNotEmpty()
                ) {
                    if (getToken().isNotEmpty()) {
                        val js = JSONObject().apply {
                            put("appealCategoryId", id.toString())
                            put("title", addTitle.text.toString())
                            put("content", addContent.text.toString())
                            put("undertaker", addUserThis.text.toString())
                            put("imgUrl", url + imagePath)
                        }

                        CoroutineScope(Dispatchers.Main).launch {
                            api.getHotLineAdd(getToken(), js.toString().toRequestBody("application/json".toMediaTypeOrNull())).apply {
                                if (this.code == "200") {
                                    runOnUiThread {
                                        this.msg.show()
                                        Log.d("Body", "onCreate: --> ${this.msg}")
                                    }
                                } else runOnUiThread {
                                    this.msg.show()
                                    Log.d("Body", "onCreate: --> ${this.msg}")
                                }
                            }
                        }
                    } else "请先登录！".show()
                } else "不能为空！".show()
            }
        }else{
            addEditText.visibility = View.VISIBLE

            addEditText.setOnClickListener {
                alert()
            }

            addPostOk.setOnClickListener {

                var getId: Int? = null
                var j = 0
                for(i in list){
                    if (tvName == i){
                        getId = listNumber[j]
                    }
                    j++
                }

                if (addTitle.text.toString().isNotEmpty() &&
                    addUserThis.text.toString().isNotEmpty() &&
                    addContent.text.toString().isNotEmpty() &&
                    addPhone.text.toString().isNotEmpty()
                ) {
                    if (getToken().isNotEmpty()) {
                        val js = JSONObject().apply {
                            put("appealCategoryId", getId)
                            put("title", addTitle.text.toString())
                            put("content", addContent.text.toString())
                            put("undertaker", addUserThis.text.toString())
                            put("imgUrl", url + imagePath)
                        }

                        CoroutineScope(Dispatchers.Main).launch {
                            api.getHotLineAdd(getToken(), js.toString().toRequestBody("application/json".toMediaTypeOrNull())).apply {
                                if (this.code == "200") {
                                    runOnUiThread {
                                        this.msg.show()
                                        Log.d("Body", "onCreate: --> ${this.msg}")
                                    }
                                } else runOnUiThread {
                                    this.msg.show()
                                    Log.d("Body", "onCreate: --> ${this.msg}")
                                }
                            }
                        }
                    } else "请先登录！".show()
                } else "不能为空！".show()
            }
        }



        /**
         * 打开相册
         */
        addImage1.setOnClickListener {
            val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
            startActivityForResult(intent, imageCode)
        }
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            imageCode -> {
                if (resultCode == Activity.RESULT_OK && data != null) {
                    data.data?.let { uri ->
                        // 将照片显示出来
                        addImage1.setImageURI(uri)
                        imagePath = getRealPathFromURI(uri)
                    }
                }
            }
        }
    }

    /**
     * Uri转换地址
     */
    private fun getRealPathFromURI(uri: Uri): String {
        val projection = arrayOf(MediaStore.Images.Media.DATA)
        val cursor: Cursor? = contentResolver.query(uri, projection, null, null, null)
        val columnIndex: Int? = cursor?.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
        cursor?.moveToFirst()
        val imagePath: String = cursor?.getString(columnIndex!!) ?: ""
        cursor?.close()
        return imagePath
    }


    /**
     * 选择分类
     */
    private fun alert(){
        // 获取布局
        val radioLayout = View.inflate(this, R.layout.gohotline_alert_radio, null)
        // 获取控件
        val radioGroup = radioLayout.findViewById<RadioGroup>(R.id.gmhotlineLIstRadio)



        // 弹窗
        AlertDialog.Builder(this).apply {
            setTitle("选择诉求类目")
            setView(radioLayout)
            runOnUiThread {
                for (i in list){
                    val radioButton = RadioButton(radioGroup.context)
                    RadioGroup.LayoutParams(100,100).apply {
                        setMargins(15,0,0,0)
                        radioButton.setPadding(80,0,0,0)
                        radioButton.text = i
                    }
                    radioButton.setOnClickListener {
                        tvName = i
                    }
                    radioGroup.addView(radioButton)
                }

            }


            setPositiveButton("确定"){ _, _ ->
                runOnUiThread {
                    addEditText.text = tvName
                }
            }
            setNegativeButton("取消"){ _, _ ->

            }
            show()
        }

    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        finish()
        return super.onOptionsItemSelected(item)
    }
}